package com.fingard.dsp.bank.directbank.cmb06.util;

/**
 * @program: ybyy-policy->JwtUtil
 * @description:
 * @author: ex_lanyixin
 * @create: 2020-05-15 11:24
 **/

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    /**
     * @description
     * @Param: [logon_name]
     * @returns: java.lang.String
     * @Author: ex_lanyixin
     * @Date: 2020/5/15 15:00
     */
    public String createToken(CMBSignInfo cmbSignInfo, String logonName) throws Exception {
        //签名发布时间
        Date createTime = new Date();
        //设置签名过期时间  5分钟
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, 15);
        Date expiresTime = nowTime.getTime();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", cmbSignInfo.getVerify());//设置算法
        map.put("typ", "JWT");//设置类型为JWT
        String token = JWT.create()
                .withHeader(map)
                .withIssuer(cmbSignInfo.getDomainName())
                .withClaim("logon_name", logonName) //可以将基本不重要的对象信息放到claims中
                .withIssuedAt(new Date())//设置签发时间
                .withExpiresAt(expiresTime)//设置过去时间 过期时间大于签发时间
                .sign(SMAlgorithm.SM3withSM2(cmbSignInfo.getVerify(), cmbSignInfo.getJwtPrivateKey()));//用公共密钥加密
        return token;
    }

    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public boolean verify(CMBSignInfo cmbSignInfo, String token, String logonName, String secret) {
        try {
            //根据密码生成JWT效验器
            Algorithm algorithm = SMAlgorithm.SM3withSM2(cmbSignInfo.getVerify(), cmbSignInfo.getJwtPrivateKey());
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("logon_name", logonName)
                    .build();
            //效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getLogonName(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("logon_name").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

}